package com.jnu.student.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.student.EditBookActivity;
import com.jnu.student.R;
import com.jnu.student.data.Book;
import com.jnu.student.data.DataBank;

import java.util.List;

public class bookItemFragment extends Fragment {

    public static final int RESULT_CODE_ADD_DATA = 996;
    private List<Book> books;
    private RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder> recyclerViewAdapter;

    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA){
                if(null==data)return;
                String bookName=data.getStringExtra("name");
                int position=data.getIntExtra("position",books.size());
                books.add(position, new Book(bookName, R.drawable.book_no_name));
                dataBank.saveData();
                recyclerViewAdapter.notifyItemInserted(position);
            }
        }
    });
    ActivityResultLauncher<Intent>  launcherEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA) {
                if(null==data)return;
                String bookName = data.getStringExtra("name");
                int position = data.getIntExtra("position", books.size());
                books.get(position).setTitle(bookName);
                dataBank.saveData();
                recyclerViewAdapter.notifyItemChanged(position);
            }
        }
    });
    private DataBank dataBank;

    public bookItemFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static bookItemFragment newInstance() {
        bookItemFragment fragment = new bookItemFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_book_item, container, false);

        initData();

        //悬浮添加键
        FloatingActionButton fabAdd=rootView.findViewById(R.id.floating_action_button_add);
        fabAdd.setOnClickListener(view -> {
            Intent intent=new Intent(this.getContext(), EditBookActivity.class);
            intent.putExtra("position",books.size());
            launcherAdd.launch(intent);
        });

        RecyclerView mainRecyclerView = rootView.findViewById(R.id.recycle_view_books);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
        mainRecyclerView.setLayoutManager(layoutManager);

        recyclerViewAdapter = new MyRecyclerViewAdapter(books);
        mainRecyclerView.setAdapter(recyclerViewAdapter);

        return rootView;
    }

    public void initData(){
        dataBank = new DataBank(this.getContext());
        books = dataBank.loadData();
    }


    private class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder> {
        private final List<Book> books;
        public MyRecyclerViewAdapter(List<Book> books) { this.books=books;}

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.book_item_holder, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            ( (MyViewHolder) holder).getImageView().setImageResource(books.get(position).getCoverResourceId());
            ( (MyViewHolder) holder).getTextViewTitle().setText(books.get(position).getTitle());
        }

        @Override
        public int getItemCount() {
            return books.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements MenuItem.OnMenuItemClickListener, View.OnCreateContextMenuListener {
            public static final int CONTEXT_MENU_ID_ADD = 1;
            public static final int CONTEXT_MENU_ID_UPDATE = CONTEXT_MENU_ID_ADD+1;
            public static final int CONTEXT_MENU_ID_DELETE = CONTEXT_MENU_ID_ADD+2;
            private final ImageView imageView;
            private final TextView textViewTitle;

            public MyViewHolder(View view) {
                super(view);
                this.imageView=view.findViewById(R.id.image_view_book_cover);
                this.textViewTitle=view.findViewById(R.id.text_view_book_title);

                itemView.setOnCreateContextMenuListener(this);

            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getTextViewTitle() {
                return textViewTitle;
            }

            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                MenuItem menuItemAdd=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_ADD,CONTEXT_MENU_ID_ADD, R.string.string_menu_add);
                MenuItem menuItemEdit=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_UPDATE,CONTEXT_MENU_ID_UPDATE, R.string.string_menu_edit);
                MenuItem menuItemDelete=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_DELETE,CONTEXT_MENU_ID_DELETE, R.string.string_menu_delete);

                menuItemAdd.setOnMenuItemClickListener(this);
                menuItemEdit.setOnMenuItemClickListener(this);
                menuItemDelete.setOnMenuItemClickListener(this);

            }

            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                int position= getAdapterPosition();
                Intent intent;

                switch(menuItem.getItemId())
                {
                    case CONTEXT_MENU_ID_ADD:
                        intent=new Intent(bookItemFragment.this.getContext(),EditBookActivity.class);
                        intent.putExtra("position",position);
                        launcherAdd.launch(intent);
                        break;

                    case CONTEXT_MENU_ID_UPDATE:
                        intent=new Intent(bookItemFragment.this.getContext(),EditBookActivity.class);
                        intent.putExtra("position",position);
                        intent.putExtra("name",books.get(position).getTitle());
                        launcherEdit.launch(intent);
                        break;
                    case CONTEXT_MENU_ID_DELETE:
                        AlertDialog.Builder alertDB = new AlertDialog.Builder(bookItemFragment.this.requireContext());
                        alertDB.setPositiveButton(R.string.string_ok, (dialogInterface, i) -> {
                            books.remove(position);
                            dataBank.saveData();
                            MyRecyclerViewAdapter.this.notifyItemRemoved(position);
                        });
                        alertDB.setNegativeButton(R.string.string_cancel, (dialogInterface, i) -> {

                        });
                        alertDB.setMessage(getString(R.string.string_confirm_delete) + books.get(position).getTitle()+"？");
                        alertDB.setTitle(R.string.hint).show();
                        break;
                }

                Toast.makeText(bookItemFragment.this.getContext(),"点击了"+menuItem.getTitle(), Toast.LENGTH_LONG).show();
                return false;
            }
        }
    }
}